﻿using System;
using System.Collections;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace PivotalTFSSync
{
	public class TFS : ITFS
	{
		private readonly string serverName;
		private readonly TeamFoundationServer tfsServer;
		private readonly WorkItemStore store;
		public TFS(string servername)
		{
			if (string.IsNullOrEmpty(servername))
			{
				throw new ArgumentException("Parameter named:servername cannot be null or empty.");
			}
			serverName = servername;
			ICredentialsProvider provider = new UICredentialsProvider();

			tfsServer = TeamFoundationServerFactory.GetServer(serverName, provider);
			if (!tfsServer.HasAuthenticated)
				tfsServer.Authenticate();
			store = (WorkItemStore)tfsServer.GetService(typeof(WorkItemStore));
		}

		public NodeCollection GetIterationPaths(string projectname)
		{
			try
			{
				return store.Projects[projectname].IterationRootNodes;
			}
			catch (Exception)
			{
				//TODO: log error. 
			}
			return null;
		}

		public void AddPivotalStoryToTFS(Story pivotalStoryToAdd, string projectname, string iterationPath)
		{
			WorkItemTypeCollection workItemTypes = store.Projects[projectname].WorkItemTypes;

			//TODO: Verify that the pivotal story isn't already replicated (by looking in the history tab, we put the pivotalid in the history list) 

			var workItem = new WorkItem(workItemTypes["Product Backlog Item"]);

			if (pivotalStoryToAdd.Type == "bug")
			{
				workItem = new WorkItem(workItemTypes["Bug"]);
			}

			workItem.Fields["Conchango.TeamSystem.Scrum.EstimatedEffort"].Value = pivotalStoryToAdd.Estimate;
			workItem.Fields["Conchango.TeamSystem.Scrum.BusinessPriority"].Value = pivotalStoryToAdd.Priority;
			workItem.Fields["Conchango.TeamSystem.Scrum.DeliveryOrder"].Value = pivotalStoryToAdd.Priority;

			workItem.Description = string.Concat(pivotalStoryToAdd.URL, Environment.NewLine, pivotalStoryToAdd.Description);
			workItem.Title = pivotalStoryToAdd.Name;
			workItem.IterationPath = iterationPath;
			workItem.Fields["History"].Value = string.Concat("PIVOTALID:", pivotalStoryToAdd.Id);

			//Add Hyper Link
			//Link most be valid!
			var hp = new Hyperlink(pivotalStoryToAdd.URL) { Comment = "Link to pivotal story." };
			workItem.Links.Add(hp);

			//Add Attachment
			//TFS will search for the file, so make sure it exists.

			//Attachment a = new Attachment(@"C:\FileToAdd.txt", "Comment....");
			//workItem.Attachments.Add(a);

			//Make sure your Work Item is Valid
			//After you finish adding all the wanted values into the Work Item make sure that all fields are Valid and your can save the Work Item, This step is to make sure that you prepare the Work Item Definition for the migration. 

			var invalidFields = new ArrayList();
			foreach (Field field in workItem.Fields)
			{
				if (!field.IsValid)
				{
					invalidFields.Add(field);
					Console.WriteLine("Invalid Field '{0}': {1}", field.Name, field.Status);
					Console.WriteLine("Current Value: '{0}'", field.Value);
				}
			}
			//There are some Invalid Fields.
			if (invalidFields.Count > 0)
			{
				Console.WriteLine("Invalid Bug Track ID:{0}", invalidFields.ToArray());
				return;
			}
			workItem.Save();
		}

		public ProjectCollection GetProjects()
		{
			try
			{
				return store.Projects;
			}
			catch (Exception)
			{
				//TODO: log error. 
			}
			return null;
		}

		//public void GetNextPriorityNumberAndPriorityStep(string projectname,out int nextPriority, out int priorityStep)
		//{
		//    //store.Projects[projectname].IterationRootNodes.


		//}
	}
}